package cn.school.job.acsys;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.school.acsys.entity.AcsSysInfo;
import cn.school.acsys.service.AccessControlSysService;
import cn.school.notice.service.FamilyNoticeService;
import cn.school.sys.entity.SysConfig;
import cn.school.sys.service.SysConfigService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @className: AccessControlSysJob
 * @author: Alex
 * @date: 2023/3/14
 **/
@Slf4j
@Component
public class AccessControlSysJob extends QuartzJobBean {
	@Autowired
	private SysConfigService sysConfigService;
	
	@Autowired
	private AccessControlSysService accessControlSysService;
	
	@Autowired
	private FamilyNoticeService familyNoticeService;
	
	@Override
	protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		log.info("查询账号门禁流水任务执行开始...........");
		
		try {
			// 获取当前时间 执行完成定时任务放入系统配置中
			Date nowDate = DateUtil.date();
			
			// 获取上一次定时任务执行的时间
			LambdaQueryWrapper<SysConfig> sysConfigCourseWrapper = new LambdaQueryWrapper<>();
			sysConfigCourseWrapper.eq(SysConfig::getParamKey, "sys.acscontrol.job.date");
			SysConfig sysConfig = sysConfigService.getOne(sysConfigCourseWrapper);
			String startDate = sysConfig.getParamValue();
			
			if (StringUtils.isEmpty(startDate)) {
				startDate = DateUtil.formatDateTime(nowDate);
			}
			
			// 查询门禁流水
			List<AcsSysInfo> flowInfo = accessControlSysService.getAccessControlFlowInfo(startDate);
			
			if (CollectionUtil.isNotEmpty(flowInfo)) {
				// 发送家长通知
				familyNoticeService.batchInsertNotices(flowInfo);
			}
			// 更新系统配置中的时间
			sysConfig.setParamValue(DateUtil.formatDateTime(nowDate));
			sysConfigService.update(sysConfig.getId(), sysConfig);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		log.info("查询账号门禁流水任务执行结束...........");
	}
}
